import json
import logging
import threading
from colorlog import ColoredFormatter
import urllib.parse
from aweirunner.utils import parser

logger = logging.getLogger(__name__)
# 创建控制台处理器
handler = logging.StreamHandler()
# 设置日志级别
handler.setLevel(logging.DEBUG)
# 创建带颜色的日志格式
formatter = ColoredFormatter(
    "%(log_color)s%(asctime)s %(name)s %(levelname)s %(message)s",
    datefmt=None,
    reset=True,
    log_colors={
        'DEBUG': 'cyan',
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'bold_red',
    },
    secondary_log_colors={},
    style='%'
)
# 将格式应用到处理器
handler.setFormatter(formatter)
# 将处理器添加到记录器
logger.addHandler(handler)
# 禁用 Django 默认的日志处理器
logger.propagate = False


class CustomRequestHandler:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 记录请求开始的日志

        logger.info(f"Request method: {request.method}, path: {request.path}")
        # logger.debug(f"Request headers: {request.headers}")

        params = request.GET if request.method == "GET" else request.POST
        params_json = json.dumps(dict(params), indent=2)
        params_json = params_json if len(params_json) > 2 else convert_to_Json(request.body.decode('utf-8'))
        # 以下步骤为了解码否则会乱码
        # 解码为 Python 字典
        decoded_dict = json.loads(params_json)
        # 再次转换为 JSON 格式的字符串
        json_output = json.dumps(decoded_dict, indent=2, ensure_ascii=False)

        logger.debug(f"Request body：{json_output}")

        response = self.get_response(request)

        # 记录请求结束的日志
        # logger.info(f"Response status: {response.status_code}")
        try:
            json_content = response.content
            json_data = json.loads(json_content.decode('utf-8'))
            logger.debug(f"Response content: {json_data}")
        except Exception as e:
            # logger.error(f"json转换失败{response.content}")
            logger.error(f"json转换失败{e}")
        # 示例日志输出
        return response
        # getlog = GetLog(request, self)
        # getlog.start()
        # getlog.join()
        # return getlog.response

def convert_to_Json(data):
    # 解析参数字符串
    parsed_params = urllib.parse.parse_qs(data)

    # 构建字典
    params_dict = {}
    for key, value in parsed_params.items():
        params_dict[key] = value[0]  # 取第一个值，因为解析的结果是列表

    result = {}
    for key, value in params_dict.items():
        keys = key.split('[')
        current = result
        for k in keys[:-1]:
            current = current.setdefault(k.strip(']'), {})
        current[keys[-1].strip(']')] = value
    return json.dumps(result, indent=2)

# 方法二采用线程的方式输出，但是会分组
class GetLog(threading.Thread):
    def __init__(self, request, that):
        super().__init__()
        self.request = request
        self.response = None
        self.that = that

    def run(self) -> None:
        logger.info(f"Request method: {self.request.method}, path: {self.request.path}")
        # logger.debug(f"Request headers: {request.headers}")
        logger.debug(f"Request body: {self.request.body.decode('utf-8')}")

        response = self.that.get_response(self.request)

        # 记录请求结束的日志
        # logger.info(f"Response status: {response.status_code}")
        try:
            json_content = response.content
            json_data = json.loads(json_content.decode('utf-8'))
            logger.debug(f"Response content: {json_data}")
        except Exception as e:
            logger.error(f"json转换失败{e}")
        # 示例日志输出
        self.response = response
